package tcln.gxtx.client.widget.grid.renderer.html;

import tcln.gxtx.client.utils.lang.GwtBooleanUtils;
import tcln.gxtx.client.widget.treegrid.model.AbstractTreeModel;

import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.Grid;

/**
 * A simple {@link HtmlGridCellRenderer} which renders an checkbox-like image. This renderer uses a special image name
 * '<b>tick-small.png</b>' (locates in 'img' folder under the web root) to show when display value is <code>true</code>.
 * Otherwise, an empty DIV is shown.
 * 
 * @param <M>
 * @author Truong Chau Lien Ngoc (lienngoc@gmail.com)
 */
public class CheckboxHtmlGridCellRenderer<M extends AbstractTreeModel> extends AbstractHtmlGridCellRenderer<M> {
    private static final int DEFAULT_MARGIN_LEFT = 4;

    /**
     * @param ownerColumn
     */
    public CheckboxHtmlGridCellRenderer(ColumnConfig ownerColumn) {
        super(ownerColumn);
        margins = new Margins(0, 0, 0, DEFAULT_MARGIN_LEFT);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String render(M model, String property, ColumnData config, int rowIndex, int colIndex, ListStore<M> store,
            Grid<M> grid) {
        return build(Boolean.valueOf(formatText(model, property)), margins);
    }

    private String formatText(M model, String property) {
        return dataFormatter.format(model, property);
    }

    private String build(Boolean value, Margins margins) {
        if (margins == null) {
            margins = new Margins(0, 0, 0, DEFAULT_MARGIN_LEFT);
        }

        // set image URL from value
        String imageUrl = "img/tick-small.png";

        StringBuilder builder = new StringBuilder();

        builder.append("<div ");
        builder.append("border=\"0\" ");
        builder.append("style=\"");

        if (GwtBooleanUtils.toBoolean(value)) {
            builder.append("background-image: url(" + imageUrl + "); ");
            builder.append("background-attachment: scroll; ");
            builder.append("background-color: transparent; ");
            builder.append("background-position: ").append(margins.left).append("px ").append(margins.top).append(
                    "px; ");
            builder.append("background-repeat: no-repeat; ");
        }

        builder.append("width: 20px; height: 13px;\">");
        builder.append("&nbsp;</div>");

        return builder.toString();
    }
}
